package com.bms.dao.impl;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.hibernate.type.DateType;
import org.hibernate.type.Type;
import org.springframework.stereotype.Repository;

import com.bms.dao.VisitStatisDao;
import com.bms.entity.VisitStatis;
import com.bms.httpModel.StatisPager;
import com.bms.httpModel.Pager.OrderType;

/**
 * @author Lan
 */
@Repository
public class VisitStatisDaoImpl extends BaseDaoImpl<VisitStatis, String> implements VisitStatisDao {
	
	@SuppressWarnings("unchecked")
	public StatisPager findByPager(StatisPager pager) {
		if (pager == null) {
			pager = new StatisPager();
		}
		Integer pageNumber = pager.getCurrPage();
		Integer pageSize = pager.getPageSize();
		String orderBy = pager.getOrderBy();
		OrderType orderType = pager.getOrderType();
		
		Criteria criteria = pager.getDetachedCriteria().getExecutableCriteria(this.getSession());
		
		//（条件查询后的）记录总数
		Long totalCount = (Long) (criteria.setProjection(Projections.countDistinct("link")).uniqueResult());
		
		//（条件查询后的）用户总数
		criteria.setProjection(null);
		Long customerTotalCount = (Long) (criteria.setProjection(Projections.countDistinct("customerIP")).uniqueResult());
		System.out.println("customerTotalCount=" + customerTotalCount);
		
		//（条件查询后的）访问量总数
		criteria.setProjection(null);
		Long visitTotalCount = (Long) (criteria.setProjection(Projections.sum("visitCount")).uniqueResult());
		System.out.println("visitTotalCount=" + visitTotalCount);
		
		criteria.setProjection(null);
		
		String hql = "min(this_.statisDate) as minStatisDate, max(this_.statisDate) as maxStatisDate";
        String[] values = new String[]{"minStatisDate", "maxStatisDate"};//定义返回值
        Type[] types = new Type[]{new DateType(), new DateType()}; //定义返回类型
        
		ProjectionList proList = Projections.projectionList();
		proList.add(Projections.sum("visitCount").as("visitCount"));
	    proList.add(Projections.groupProperty("link").as("statisLink"));
//	    proList.add(Projections.groupProperty("customerIP").as("customerIP"));
	    proList.add(Projections.sqlProjection(hql, values, types));
	    
		criteria.setProjection(proList);
		criteria.setResultTransformer(new AliasToBeanResultTransformer(VisitStatis.class));
		
		criteria.setFirstResult((pageNumber - 1) * pageSize);
		criteria.setMaxResults(pageSize);
		if (StringUtils.isNotBlank(orderBy)) {
			if (orderType == OrderType.asc) {
				criteria.addOrder(Order.asc(orderBy));
			} else {
				criteria.addOrder(Order.desc(orderBy));
			}
		}
		pager.setTotalCount(totalCount.intValue());
		pager.setCustTotalCount(customerTotalCount);
		pager.setVisitTotalCount(visitTotalCount);
		pager.setList(criteria.list());
		return pager;
	}
}